//
//  CategorySortView.swift
//  KoiAccounting
//
//  Created by 纪洪文 on 01.04.25.
//

import SwiftUI

struct CategorySortView: View {
    
    @Environment(\.presentationMode) var presentationMode
    
    @State var title = "类别排序"
    
    @StateObject var viewModel = CategorySortViewModel()
    
    var selectedCategory: AccountingCategory? = nil
    
    var categoryType: CategoryType
    
    init(selectedCategory: AccountingCategory) {
        self.selectedCategory = selectedCategory
        self.categoryType = selectedCategory.getCategoryType()
    }
    
    var body: some View {
        VStack {
            KoiToolbarView(title: $title).padding(.top, 10)
            List {
                ForEach(viewModel.categoryList.indices,id:\.self) { index in
                    let category = viewModel.categoryList[index]
                    CategoryManagerItemView(item: category, moreIconClick: {clickItem in })
                        .listRowSeparator(.hidden)
                        .listRowInsets(EdgeInsets())
                        .listRowBackground(Color.clear)
                        .padding(EdgeInsets(top: 10, leading: 14, bottom: 10, trailing: 10))
                        .background(Color.koiColorBackgroundItem)
                        .cornerRadius(16)
                        .padding(.vertical, 5)
                }
                .onMove(perform: move)
            }
            .listStyle(.plain)
            .padding(EdgeInsets(top: 0, leading: 20, bottom: 0, trailing:20)) // 去除边距
            .ignoresSafeArea(.container, edges: .bottom)
        }
        .background(Color.koiColorBackground)
        .navigationBarBackButtonHidden()
        .onAppear {
            print("categoryType \(categoryType)")
            if (selectedCategory?.parentId != nil) {
                viewModel.loadSubCategorys(parentId: selectedCategory?.parentId ?? "")
            } else {
                viewModel.loadCategorys(type: categoryType.rawValue)
            }
        }
    }

    private func move(from source: IndexSet, to destination: Int) {
        viewModel.categoryList.move(fromOffsets: source, toOffset: destination)
        print("source \(source) destination \(destination) ")
        viewModel.updateCategoryOrder()
    }
}

#Preview {
    CategorySortView(selectedCategory: AccountingCategory(type: CategoryType.expense.rawValue))
}
